// 两种调用方式
// var template1="我是{0}，今年{1}了";
// var template2="我是{name}，今年{age}了";
// var result1=template1.format("loogn",22);
// var result2=template2.format({name:"loogn",age:22});
String.prototype.format = function(args) {
    var result = this;
    if (arguments.length > 0) {
        if (arguments.length == 1 && typeof(args) == "object") {
            for (var key in args) {
                if (args[key] != undefined) {
                    var reg = new RegExp("({" + key + "})", "g");
                    result = result.replace(reg, args[key]);
                }
            }
        } else {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] != undefined) {
                    var reg = new RegExp("({[" + i + "]})", "g");
                    result = result.replace(reg, arguments[i]);
                }
            }
        }
    }
    return result;
};
String.prototype.replaceAll = function(s1, s2) {　　
    return this.replace(new RegExp(s1, "gm"), s2);
};

var myStrs = {}; //本地化信息
var myCommon = {
    loadingUrls: [],
    gameIcon: '/img/common/game-icon.png?v=d29ee83e66',
    singleNumber: 1,
    getSingleNumber: function() {
        return this.singleNumber++;
    },
    getQueryString: function(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    },
    getLocalStorage: function(name) {
        if (window.localStorage) {
            var storeData = window.localStorage[name];
            if (!storeData) {
                return '';
            }
            var value = storeData.split('&&&')[0];
            var expires = storeData.split('&&&')[1];
            if (expires) {
                var now = new Date().getTime();
                if (expires < now) {
                    window.localStorage[name] = '';
                    return '';
                }
            }

            return value;
        } else {
            return myCommon.getCookie(name);
        }
    },
    setLocalStorage: function(name, value, expires) {
        if (arguments.length == 1) {
            return;
        }
        if (window.localStorage) {
            if (expires) {
                var now = new Date();
                now = now.getTime();
                var totalExpires = now;
                totalExpires = totalExpires + expires; //* 24 * 3600 * 1000;
                window.localStorage[name] = value + '&&&' + totalExpires;
            } else {
                window.localStorage[name] = value;
            }
        } else {
            myCommon.setCookie(name, value, expires);
        }
    },
    getCookie: function(name) {
        var start = document.cookie.indexOf(name + "=");
        var len = start + name.length + 1;
        if ((!start) && (name != document.cookie.substring(0, name.length))) {
            return '';
        }
        if (start == -1) return '';
        var end = document.cookie.indexOf(';', len);
        if (end == -1) end = document.cookie.length;

        return unescape(document.cookie.substring(len, end));
    },
    setCookie: function(name, value, expires, path, domain, secure) {
        var today = new Date();
        today.setTime(today.getTime());
        var expiresDate = new Date(today.getTime() + (expires));
        document.cookie = encodeURIComponent(name) + '=' + escape(value) + ((expires) ? ';expires=' + expiresDate.toGMTString() : '') +
            ((path) ? ';path=' + path : '') + ((domain) ? ';domain=' + domain : '') + ((secure) ? ';secure' : '');
    },
    //格式化日期,
    formatDate: function(date, format) {
        format = format || 'yyyy-MM-dd'
        if (typeof date == 'number') {
            date = new Date(date);
        }
        var map = {
            "M": date.getMonth() + 1, //月份 
            "d": date.getDate(), //日 
            "h": date.getHours(), //小时 
            "m": date.getMinutes(), //分 
            "s": date.getSeconds(), //秒 
            "q": Math.floor((date.getMonth() + 3) / 3), //季度 
            "S": date.getMilliseconds() //毫秒 
        };
        format = format.replace(/([yMdhmsqS])+/g, function(all, t) {
            var v = map[t];
            if (v !== undefined) {
                if (all.length > 1) {
                    v = '0' + v;
                    v = v.substr(v.length - 2);
                }
                return v;
            } else if (t === 'y') {
                return (date.getFullYear() + '').substr(4 - all.length);
            }
            return all;
        });
        return format;
    },
    showLoading: function(container) {
        var maskBody = container ? $(container) : $(window.document.body);
        if (maskBody.length == 0) {
            return;
        }
        var singleNumber = maskBody.data('singleNumber');
        if (!singleNumber) {
            singleNumber = myCommon.getSingleNumber();
            maskBody.data('singleNumber', singleNumber);
        }
        var loadingId = 'my-loading-' + singleNumber;
        var loading = $('#' + loadingId);
        if (loading.length == 0) {
            var htmlTemplate = '<div id="{0}" class="my-mask" z-index:{1};"><div class="my-loading"></div></div>';
            maskBody.append(htmlTemplate.format(loadingId, 3000 + singleNumber * 2));
            loading = $('#' + loadingId);
        }
        loading.removeAttr('style').show();
        if (container && maskBody.get(0) !== document.body) {
            loading.css({
                position: 'absolute',
                top: maskBody.position().top,
                left: maskBody.position().left,
                width: maskBody.innerWidth(),
                height: maskBody.innerHeight()
            });
        }
    },
    hideLoading: function(container) {
        var maskBody = null;
        if (container) {
            maskBody = $(container);
        } else {
            maskBody = $(window.document.body);
        }
        if (maskBody.length == 0) {
            return;
        }
        var singleNumber = maskBody.data('singleNumber');
        $('#my-loading-' + singleNumber).hide();
    },
    showConfirm: function(args) {
        args.type = 'confirm';
        args.isFixed = true;
        args.width = args.width || 364;
        args.buttonText = args.okButtonText || args.buttonText || myStrs['ok'];
        args.content = args.content ? '<div class="message-content">{0}</div>'.format(args.content) : '';
        if (args.caption) {
            args.content = '<div class="message-title">{0}</div>'.format(args.caption) + args.content;
        }
        myCommon.showPopup(args);
    },
    showMessage: function(args) {
        if (typeof args === "string") {
            args = { content: args };
        }
        args.type = 'info';
        args.isFixed = true;
        args.width = args.width || 364;
        args.buttonText = args.okButtonText || args.buttonText || myStrs['known'];
        args.content = args.content ? '<div class="message-content">{0}</div>'.format(args.content) : '';
        if (args.caption) {
            args.content = '<div class="message-title">{0}</div>'.format(args.caption) + args.content;
        }
        myCommon.showPopup(args);
    },
    showPopup: function(args) {
        if ($('#popup-mask').length == 0) {
            var builder = '<div id="popup-mask" class="my-mask"></div>';
            builder += '<div id="popup-area" class="my-popup">';
            builder += '<div id="popup-header" class="popup-header">';
            builder += '<div id="popup-title" class="popup-title"></div>';
            builder += '<a id="popup-close-button" class="close-button"></a></div>';
            builder += '<div id="popup-content" class="popup-content"></div>';
            builder += '<div id="popup-buttons" class="popup-buttons">';
            builder += '<a id="popup-ok-button" class="my-btn">'
            builder += myStrs['ok'] + '</a>';
            builder += '<a id="popup-cancel-button" class="my-btn btn-grey my-lm" style="margin-right:15px;">'
            builder += myStrs['cancel'] + '</a></div></div>';
            $(document.body).append(builder);
        }

        $('#popup-close-button').unbind().click(function() {
            myCommon.hidePopup();
            if (args.onClose) {
                args.onClose.call(window);
            }
        });
        if (args.type == 'info' || args.type == 'confirm') {
            var okButton = $('#popup-ok-button');
            var cancelButton = $('#popup-cancel-button');
            cancelButton.hide();
            $('#popup-buttons').show();
            args.buttonText = args.okButtonText || args.buttonText || myStrs['ok'];
            if (args.okButtonClass) {
                okButton.addClass(args.okButtonClass);
            }
            okButton.text(args.buttonText);
            okButton.unbind().click(function() {
                myCommon.hidePopup();
                if (args.onOKClick) {
                    args.onOKClick.call(window);
                }
                if (args.onClose) {
                    args.onClose.call(window);
                }
            });

            if (args.type == 'confirm') {
                cancelButton.show();
                if (args.cancelButtonClass) {
                    cancelButton.addClass(args.cancelButtonClass);
                }
                args.cancelButtonText = args.cancelButtonText || myStrs['cancel'];
                cancelButton.text(args.cancelButtonText);
                cancelButton.unbind().click(function() {
                    myCommon.hidePopup();
                    if (args.onCancelClick) {
                        args.onCancelClick.call(window);
                    }
                    if (args.onClose) {
                        args.onClose.call(window);
                    }
                });
            }
        } else {
            $('#popup-buttons').hide();
        }
        var popup = $('#popup-area');
        popup.removeAttr('style');
        if (args.className) {
            popup.addClass(args.className);
        } else {
            popup.attr('class', 'my-popup');
        }
        if (args.width) {
            popup.width(args.width);
        }
        var popupHeader = $('#popup-header');
        if (args.hasHeader === false) {
            popupHeader.hide();
        } else {
            popupHeader.show();
            if (args.title == undefined || args.title == null) {
                args.title = myStrs['info'];
            }
            $('#popup-title').html(args.title);
        }
        if (args.content) {
            $('#popup-content').html(args.content);
        }
        popup.show();
        $('#popup-mask').show();
        var screenHeight = $(window).height(); //当前浏览器窗口的 宽高   
        var scrolltop = $(document.body).scrollTop(); //获取当前窗口距离页面顶部高度   
        var popupTop = (screenHeight - popup.height()) / 2 + scrolltop;
        var popupLeft = ($(window).width() - popup.width()) / 2;
        var positionval = "absolute";
        if (args.isFixed) {
            popupTop = (screenHeight - popup.height()) / 2;
            positionval = "fixed";
        }
        popup.css({
            position: positionval,
            top: popupTop + 'px',
            left: popupLeft + 'px'
        });
        if (args.closeTimeout) {
            setTimeout(function() {
                myCommon.hidePopup();
            }, args.closeTimeout);
        }
    },
    hidePopup: function() {
        $('#popup-mask').hide();
        $('#popup-area').hide();
    },
    ajax: function(http, args) {
        if (args) {
            addAjaxLoading();
            return ngAjax(); //angular ajax
        } else {
            args = http; //angular ajax
            addAjaxLoading();
            return jqAjax();
        }

        function jqAjax() {
            var options = {
                type: args.type || 'GET',
                dataType: args.dataType || 'json',
                async: args.async == false ? false : true,
                data: args.data || {},
                url: args.url,
                success: successCallback,
                error: errorCallback
            };
            if (args.type == 'POST' || args.type == 'post') {
                options.contentType = 'application/json; charset=utf-8';
                options.data = JSON.stringify(options.data);
            }

            return $.ajax(options);
        }

        function ngAjax() {
            if (args.type == 'post' || args.type == 'POST') {
                http.post(args.url, args.data).success(successCallback).error(errorCallback);
            } else {
                http.get(args.url, args.data).success(successCallback).error(errorCallback);
            }
        }

        function successCallback(response) {
            //处理成功的响应
            removeAjaxLoading();
            if (args.success) {
                args.success(response);
            }
            if (args.complete) {
                args.complete(response);
            }
        }

        function errorCallback(response) {
            //处理失败后的响应
            removeAjaxLoading();
            if (args.error) {
                args.error(response);
            }
            if (args.complete) {
                args.complete(response);
            }
        }

        function addAjaxLoading() {
            if (args.loading === true) {
                myCommon.removeItem(myCommon.loadingUrls, args.url);
                myCommon.loadingUrls.push(args.url);
                myCommon.showLoading();
            } else if (args.loading) {
                myCommon.showLoading(args.loading);
            }
        }

        function removeAjaxLoading() {
            if (args.loading === true) {
                myCommon.removeItem(myCommon.loadingUrls, args.url);
                if (myCommon.loadingUrls.length == 0) {
                    myCommon.hideLoading();
                }
            } else if (args.loading) {
                myCommon.hideLoading(args.loading);
            }
        }
    },
    //通过字段key,查找数据的某条数据
    getItem: function(array, value, key) {
        for (var i = 0; i < array.length; i++) {
            var item = array[i];
            if (item[key] == value) {
                return item;
            }
        }
        return null;
    },
    removeItem: function(array, value, key) {
        if (key) {
            for (var i = 0; i < array.length; i++) {
                var item = array[i];
                if (item[key] == value) {
                    array.splice(i, 1);
                    break;
                }
            }
        } else {
            var start = $.inArray(value, array);
            if (start > -1) {
                array.splice(start, 1);
            }
        }
    },
    initApp: function(hasRoute) {
        if (hasRoute) {
            window.myApp = angular.module('my-app', ['ngRoute', 'oc.lazyLoad']);
        } else {
            window.myApp = angular.module('my-app', []);
        }
        myApp.run(['$rootScope', function(rootScope) {
            rootScope.myStrs = myStrs;
            //严格过滤
            rootScope.checkEqual = function(actual, expected) {
                if (!expected || expected == 'all' || expected == '-1') {
                    return true;
                }
                return actual == expected;
            };
            rootScope.getTypeName = function(val, type) {
                return $.trans[type](val);
            };
        }]);
        myApp.config(['$controllerProvider', '$compileProvider', '$filterProvider', '$provide',
            function($controllerProvider, $compileProvider, $filterProvider, $provide) {
                myApp.controller = $controllerProvider.register;
                myApp.directive = $compileProvider.directive;
                myApp.filter = $filterProvider.register;
                myApp.factory = $provide.factory;
                myApp.service = $provide.service;
                myApp.value = $provide.value;
                myApp.constant = $provide.constant;
            }
        ]);
        myApp.directive('ngFinished', ['$timeout', function($timeout) {
            return {
                restrict: 'A',
                link: function(scope, element, attr) {
                    if (!scope[attr.ngFinished]) {
                        return;
                    }
                    if (scope.$last === true) {
                        setTimeout(scope[attr.ngFinished], 100); //Calling a scoped method
                    } else if (scope.$last === undefined) {
                        setTimeout(scope[attr.ngFinished], 100); //Calling a scoped method
                    }
                }
            };
        }]);
        myApp.filter('trustHtml', ['$sce', function($sce) {
            return function(input) {
                return $sce.trustAsHtml(input);
            }
        }]);
    },
    load: function(srcs) {
        return {
            // deps: ['$q', function($q) {
            //         var defer = $q.defer();
            //         require(srcs, defer.resolve);
            //         return defer.promise;
            //     }]
            deps: ['$ocLazyLoad', '$q', function($ocLazyLoad, $q) {
                srcs = angular.isArray(srcs) ? srcs : [srcs];
                var deferred = $q.defer();
                var promise = deferred.promise;
                angular.forEach(srcs, function(src) {
                    promise = promise.then(function() {
                        var files = myConfig.getFiles(src);
                        return $ocLazyLoad.load(files || src);
                    });
                });
                deferred.resolve();
                return promise;
            }]
        }
    },
    initStr: function() { //国际化
        $.ajax("/data/str." + window.myLanguage + ".json", {
            async: false,
            success: function(data) {
                window.myStrs = data;
            }
        });
    },
    toDate: function(dateStr) { //2016-06-06 12:30:30
        var splitIndex = dateStr.indexOf(' ');
        if (splitIndex > 0) {
            dateStr = dateStr.substr(0, splitIndex);
        }
        var dateArray = dateStr.split('-');
        return new Date(parseInt(dateArray[0]), parseInt(dateArray[1]) - 1, parseInt(dateArray[2]));
    }
};

var myConfig = {
    baseUrl: window.staticPath,
    // urlArgs: "?v=1.0",
    paths: {
        'common': 'js/common.js?v=468822ba64',
        'jquery': 'lib/jquery.min.js',
        'angular': 'lib/angular/angular.min.js',
        'angular-route': 'lib/angular/angular-route.min.js',
        'validator': 'js/my-validator.js?v=fbc728be43',
        'menu': 'js/my-menu.js?v=b389dd9f3c',
        'progress': 'js/my-progress.js?v=21335cb122',
        'slide': 'js/my-slide.js?v=d9eaf64b1a',
        'icheck': ['lib/checkbox/skins/square/blue.css', 'lib/checkbox/icheck.js'],
        'mutiselect': ['lib/mutiselect/multiple-select.css', 'lib/mutiselect/multiple-select.js'],
        'uploader': ['lib/webuploader.html5only.min.js', 'js/my-upload.js?v=c83881999e'],
        'chart': ['lib/highstock.js', 'js/my-chart.js?v=2ca2da568a'],
        'picker': ['lib/datetimepicker/css/BeatPicker.css', 'lib/datetimepicker/js/BeatPicker.js'],
        'fullpage': ['lib/fullpage/jquery.fullpage.min.css', 'lib/fullpage/jquery.fullpage.min.js']
    },
    getFiles: function(name) {
        var files = this.paths[name];
        if (!files) {
            return '';
        }
        if (!$.isArray(files)) {
            return [this.baseUrl + files];
        }
        var result = [];
        for (var i = 0; i < files.length; i++) {
            result.push(this.baseUrl + files[i]);
        }
        return result;
    }
};

(function($) {
    if (!$) {
        return;
    }
    //去除text的前后空格
    $.fn.trimVal = function() {
        var val = this.val();
        return val ? $.trim(val) : val;
    };
    myCommon.initStr(); //初始化Strings
})(jQuery);
